/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect, useRef, useState } from 'react';
import { message, Space, Popconfirm, Row, Col } from 'antd';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import ProCard from '@ant-design/pro-card';
import DragTable from '@/components/DragTable';
import ProTable from '@ant-design/pro-table';
import KbAuth from '@/components/_pages/jdk/registerTable/compontents/KbAuth';
import KbRefuseModal from '@/components/_pages/jdk/registerTable/compontents/KbRefuseModal';
import KbAddModal from '@/components/_pages/jdk/registerTable/compontents/KbAddModal';
import KbBindModal from '@/components/_pages/jdk/registerTable/compontents/KbBindModal';
import KbTipsModal from '@/components/_pages/jdk/registerTable/compontents/KbTipsModal';
import KbLogModal from '@/components/_pages/jdk/registerTable/compontents/KbLogModal';
import KbSavePriceModal from '@/components/_pages/jdk/registerTable/compontents/KbSavePriceModal';
import type { ConnectState } from '@/models/connect';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import type { Location } from 'umi';
import type { BasePriceItem } from '@/components/_pages/jdk/index.d';
import type { REGISTER_COLUMNS } from '@/components/_pages/jdk/index.d';
import {
  saveUnBlack,
  saveUnBind,
  getDetailData,
  getTransportList,
  getCarryList,
  setDeliveryStatus,
} from '@/services/jdk/register';
import { formatDetailVal } from '@/components/_pages/jdk/utils/index.appRegister';
import { history, useLocation, useSelector } from 'umi';
import styles from './details.less';
import { isArray } from 'lodash';
import { getPriceRender } from '@/components/_pages/jdk/addLeague/_utils';
import KbBindTakeawayModal from '@/components/_pages/jdk/registerTable/compontents/KbBindTakeawayModal';
import KbLssAddModal from '@/components/_pages/jdk/registerTable/compontents/KblssAddModal';
import KbSfDrawer from '@/components/_pages/jdk/registerTable/compontents/KbSfDrawer';
import KbPlatTable from '@/components/_pages/jdk/addLeague/compinents/KbPlatTable';

const Index = () => {
  const { query: urlParams }: any = useLocation() as Location;
  const shopActionRef = useRef<ActionType>();
  const actionRef = useRef<ActionType>();
  const detailType = {
    phone: '商家账号',
    league_source_name: '来源',
    shop_address: '商家地址',
    is_black: '登录状态',
    shop_name: '商家名称',
    created_at: '注册时间',
    league_name: '所属服务商',
    chain_name: '所属连锁商',
    delivery_status: '发单状态',
    shunfen: '顺丰独占账号',
  };
  const [record, setRecord] = useState<REGISTER_COLUMNS | any>({});
  const [userId, setUserId] = useState<string>('');
  const [visible, setVisible] = useState<boolean>(false);
  const [lssVisible, setLssVisible] = useState<boolean>(false);
  const [hasShop, setHasShop] = useState<boolean>(false);
  const [tipVisible, setTipVisible] = useState<boolean>(false);
  const [logVisible, setLogVisible] = useState<boolean>(false);
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const handleBindModal = (user_id: string, type: string) => {
    setUserId(user_id);
    if (type == 'league') {
      setVisible(true);
    } else {
      setLssVisible(true);
    }
  };
  const onCancel = () => {
    setVisible(false);
    setLssVisible(false);
  };
  const queryTable = async (values: any) => {
    const { current: page, pageSize } = values;
    const { code, data } = await getTransportList({
      page,
      pageSize,
      user_id: urlParams?.user_id,
    });
    if (code == 0) {
      setHasShop(!!data.list.length);
      return {
        data: data.list,
        total: data.total,
      };
    } else {
      return {};
    }
  };
  const queryCarryTable = async () => {
    const { code, data } = await getCarryList({
      user_id: urlParams?.user_id,
    });
    if (code == 0 && isArray(data)) {
      return {
        data: data || [],
      };
    } else {
      return {};
    }
  };

  const getDetailDatas = async () => {
    const { user_id } = urlParams;
    const { code, data, msg } = await getDetailData({ user_id });
    if (code == 0) {
      const { shop_list, shop_address_list, is_black, delivery_status } = data;
      const shop_name = isArray(shop_list) && shop_list.length > 0 ? shop_list[0].shop_name : '-';
      const shop_address = isArray(shop_address_list) ? shop_address_list[0] : '-';
      const black = is_black == '1' ? '已禁止' : '正常';
      const deliveryStatus = delivery_status == '1' ? '正常' : '已禁止'; //发单状态
      setRecord({
        ...data,
        shop_name,
        shop_address,
        is_black: black,
        delivery_status: deliveryStatus,
      });
    } else {
      message.error(msg);
    }
  };

  const detailColumns: ProColumns<any>[] = [
    {
      title: '店铺名称',
      dataIndex: 'shop_name',
      width: 200,
      search: false,
      align: 'center',
      ellipsis: true,
    },
    {
      title: '手机号',
      dataIndex: 'contact_mobile',
      width: 120,
      search: false,
      align: 'center',
      ellipsis: true,
    },
    {
      title: '地址',
      dataIndex: 'completely_addr',
      width: 320,
      search: false,
      align: 'center',
      ellipsis: true,
    },
    {
      title: '已绑运力',
      dataIndex: 'delivery_name',
      search: false,
      width: 220,
      align: 'center',
      ellipsis: true,
    },
    {
      title: '操作',
      align: 'center',
      width: winSize ? 120 : 60,
      fixed: 'right',
      valueType: 'option',
      render: (_, record_) => {
        return (
          <Space key='re'>
            <KbBindModal item={record_} hasShopId tableRef={shopActionRef}>
              <a>绑定运力</a>
            </KbBindModal>
            <KbBindTakeawayModal item={record_} tableRef={shopActionRef}>
              <a>绑定外卖平台</a>
            </KbBindTakeawayModal>
          </Space>
        );
      },
    },
  ];
  const carryColumns: ProColumns<BasePriceItem>[] = [
    {
      title: '运力',
      dataIndex: 'brand_name',
      width: 60,
      search: false,
      align: 'center',
      ellipsis: true,
    },
    {
      title: 'admin对所属服务商设置的基础价格',
      dataIndex: 'admin_league_base_price',
      width: 160,
      search: false,
      align: 'center',
      ellipsis: true,
      render: (_, record_) => {
        const { admin_league_base_price = '' } = record_;
        if (admin_league_base_price === '') {
          return '无';
        }
        return (
          (admin_league_base_price === '' ? '-' : getPriceRender(Number(admin_league_base_price))) +
          '元/单'
        );
      },
    },
    {
      title: '服务商给商家设置的基础价',
      dataIndex: 'league_base_price',
      width: 120,
      search: false,
      align: 'center',
      ellipsis: true,
      render: (_, record_) => {
        const { league_base_price = '' } = record_;
        if (league_base_price === '') {
          return '无';
        }
        return (
          (league_base_price === '' ? '-' : getPriceRender(Number(league_base_price))) + '元/单'
        );
      },
    },
    {
      title: 'admin对商家设置的基础价',
      dataIndex: 'admin_base_price',
      search: false,
      width: 120,
      align: 'center',
      ellipsis: true,
      render: (_, record_) => {
        const { admin_base_price = '' } = record_;
        if (admin_base_price === '') {
          return '无';
        }
        return (admin_base_price === '' ? '-' : getPriceRender(Number(admin_base_price))) + '元/单';
      },
    },
    {
      title: '商家当前自运力生效基础价',
      dataIndex: 'real_base_price',
      search: false,
      width: 120,
      align: 'center',
      ellipsis: true,
      render: (_, record_) => {
        const { real_base_price = '-' } = record_;
        if (real_base_price === '') {
          return '无';
        }
        return (real_base_price === '' ? '-' : getPriceRender(Number(real_base_price))) + '元/单';
      },
    },
    {
      title: '操作',
      align: 'center',
      width: winSize ? 120 : 60,
      fixed: 'right',
      valueType: 'option',
      render: (_, record_) => {
        return (
          <Space key='re'>
            <KbSavePriceModal item={record_} user_id={urlParams?.user_id} tableRef={actionRef}>
              <a>设置基础价</a>
            </KbSavePriceModal>
          </Space>
        );
      },
    },
  ];
  const handleUnBlack = (user_id: string) => {
    saveUnBlack({ user_id }).then((res) => {
      const { code, msg } = res;
      if (code == 0) {
        getDetailDatas();
        message.success('解除禁止登录成功！');
      } else {
        message.error(msg);
      }
    });
  };
  const unBind = (values: { user_id: string; type: string }) => {
    saveUnBind(values).then((res) => {
      const { code, msg } = res;
      if (code == 0) {
        getDetailDatas();
        message.success('解除绑定成功！');
      } else {
        message.error(msg);
      }
    });
  };

  const handleDeliveryStatus = () => {
    const { user_id, delivery_status } = record;
    setDeliveryStatus({ user_id, status: delivery_status === '正常' ? '2' : '1' }).then((res) => {
      const { code, msg } = res;
      if (code == 0) {
        getDetailDatas();
        message.success('操作成功！');
      } else {
        message.error(msg);
      }
    });
  };

  const goBack = () => history.goBack();
  useEffect(() => {
    getDetailDatas();
  }, [urlParams]);
  return (
    <PageContainer className={styles.main}>
      <ProCard
        title='商家详情'
        extra={[
          <a key='goBack' onClick={goBack}>
            返回上一页
          </a>,
        ]}
        style={{
          borderBottom: '24px solid #eef0f3',
        }}
      >
        <Row>
          {Object.keys(detailType).map((item) => {
            const key = detailType[item];
            const value = formatDetailVal(record, item);
            const deliveryStatus = record.delivery_status == '正常';
            const { user_id, chain_user_id } = record;
            return (
              <Col xxl={6} lg={12} xs={24} key={item}>
                <Row>
                  <Col>
                    <strong>{key}：</strong>
                  </Col>
                  <Col>
                    <Space direction={winSize === 'xs' ? 'vertical' : 'horizontal'}>
                      <span>{value}</span>
                      {item == 'league_name' ? (
                        record.league_id != '0' ? (
                          <Popconfirm
                            title='你确定取消绑定吗？'
                            key='pop'
                            onConfirm={unBind.bind(null, { user_id, type: 'league' })}
                          >
                            <a style={{ color: 'red' }}>解除关系</a>
                          </Popconfirm>
                        ) : (
                          <a onClick={handleBindModal.bind(null, user_id, 'league')}>绑定服务商</a>
                        )
                      ) : item == 'chain_name' ? (
                        chain_user_id != '0' ? (
                          <Popconfirm
                            title='你确定取消绑定吗？'
                            key='pop'
                            onConfirm={unBind.bind(null, { user_id, type: 'chain' })}
                          >
                            <a style={{ color: 'red' }}>解除关系</a>
                          </Popconfirm>
                        ) : (
                          <a onClick={handleBindModal.bind(null, user_id, 'chain')}>绑定连锁商</a>
                        )
                      ) : item == 'is_black' ? (
                        record.is_black == '已禁止' ? (
                          <Popconfirm
                            title='你确定允许登录吗？'
                            key='popLogin'
                            onConfirm={handleUnBlack.bind(null, record.user_id)}
                          >
                            <a>允许登录</a>
                          </Popconfirm>
                        ) : (
                          <KbRefuseModal
                            key='notLogin'
                            item={record}
                            successCallBack={getDetailDatas}
                          >
                            <a style={{ color: 'red' }}>禁止登录</a>
                          </KbRefuseModal>
                        )
                      ) : item == 'delivery_status' ? (
                        <Popconfirm
                          title={`你确定${deliveryStatus ? '禁止' : '允许'}发单吗？`}
                          key='popLogin'
                          onConfirm={handleDeliveryStatus}
                        >
                          <a style={{ color: deliveryStatus ? 'red' : '' }}>
                            {deliveryStatus ? '禁止发单' : '允许发单'}
                          </a>
                        </Popconfirm>
                      ) : item == 'shunfen' ? (
                        <KbSfDrawer
                          winSize={winSize}
                          onComplete={getDetailDatas}
                          queryData={{ user_id: record.user_id, type: 'merchant' }}
                          record={record[item]}
                        ></KbSfDrawer>
                      ) : null}
                    </Space>
                  </Col>
                </Row>
              </Col>
            );
          })}
        </Row>
      </ProCard>
      <DragTable>
        <ProTable
          cardProps={{
            title: '店铺设置',
            extra: !hasShop && [
              <KbBindModal item={record} tableRef={shopActionRef}>
                <a>绑定运力</a>
              </KbBindModal>,
            ],
          }}
          rowKey='id'
          className={styles.detailTable}
          actionRef={shopActionRef}
          search={false}
          columns={detailColumns}
          request={queryTable}
          scroll={{ x: 980 }}
        />
      </DragTable>
      <DragTable>
        <ProTable
          cardProps={{
            title: (
              <Space>
                自运力基础价格设置
                <a onClick={() => setTipVisible(true)}>
                  <QuestionCircleOutlined />
                </a>
              </Space>
            ),
            extra: [
              <a key='goBack' onClick={() => setLogVisible(true)}>
                操作记录
              </a>,
            ],
            style: { marginTop: 24 },
          }}
          rowKey='id'
          className={styles.detailTable}
          actionRef={actionRef}
          search={false}
          columns={carryColumns}
          request={queryCarryTable}
          scroll={{ x: 700 }}
        />
      </DragTable>

      <KbPlatTable
        type='shop'
        user_id={record.user_id}
        league_id={record.league_id}
        style={{ marginTop: 24 }}
      />

      <KbAuth
        record={record}
        successCallBack={() => {
          getDetailDatas();
          actionRef.current?.reload(true);
        }}
      />

      <KbAddModal
        visible={visible}
        userId={userId}
        successCallBack={getDetailDatas}
        onCancel={onCancel}
      />
      <KbLssAddModal
        visible={lssVisible}
        userId={userId}
        successCallBack={getDetailDatas}
        onCancel={onCancel}
      />
      <KbLogModal visible={logVisible} setVisible={setLogVisible} user_id={urlParams?.user_id} />
      <KbTipsModal visible={tipVisible} setVisible={setTipVisible} />
    </PageContainer>
  );
};

export default Index;
